﻿using HuiZe.education.Model;
using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;

namespace HuiZe.education.View
{
    /// <summary>
    /// PART_MyPackage_Item_Horizontal.xaml 的交互逻辑
    /// </summary>
    public partial class PART_MyPackage_Item_Horizontal : UserControl
    {
        public ResMyBkResourceDetailItemModel Data
        {
            get { return (ResMyBkResourceDetailItemModel)GetValue(DataProperty); }
            set { SetValue(DataProperty, value); }
        }

        // Using a DependencyProperty as the backing store for Data.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty DataProperty =
            DependencyProperty.Register("Data", typeof(ResMyBkResourceDetailItemModel), typeof(PART_MyPackage_Item_Horizontal), new PropertyMetadata(null, (sender, e) =>
             {
                 PART_MyPackage_Item_Horizontal _item = (PART_MyPackage_Item_Horizontal)sender;
                 ResMyBkResourceDetailItemModel _model = null;
                 if (e.NewValue != null && e.NewValue is ResMyBkResourceDetailItemModel)
                     _model = e.NewValue as ResMyBkResourceDetailItemModel;

                 _item.Load(_model);
             }));

        /// <summary>
        /// 下载
        /// </summary>
        public Action<ResMyBkResourceDetailItemModel> DownloadCallback { get; set; }
        /// <summary>
        /// 删除
        /// </summary>
        public Action<ResMyBkResourceDetailItemModel> DeleteCallback { get; set; }
        /// <summary>
        /// 分享
        /// </summary>
        public Action<ResMyBkResourceDetailItemModel> ShareCallback { get; set; }
        /// <summary>
        /// 修改
        /// </summary>
        public Action<ResMyBkResourceDetailItemModel> EditCallback { get; set; }
        /// <summary>
        /// 置顶
        /// </summary>
        public Action<ResMyBkResourceDetailItemModel> TopCallback { get; set; }
        /// <summary>
        /// 上课
        /// </summary>
        public Action<ResMyBkResourceDetailItemModel> LessonCallback { get; set; }

        public PART_MyPackage_Item_Horizontal()
        {
            InitializeComponent();
            PART_Lesson.Click += PART_Lesson_Click;
            PART_Top.Click += PART_Top_Click;
            PART_Edit.Click += PART_Edit_Click;
            PART_Share.Click += PART_Share_Click;
            PART_Delete.Click += PART_Delete_Click;
            PART_Download.Click += PART_Download_Click;
        }

        public void Load(ResMyBkResourceDetailItemModel _data)
        {
            if (_data == null) return;

            //BitmapImage _bmp = new BitmapImage();
            //_bmp.CacheOption = BitmapCacheOption.OnLoad;
            //_bmp.BeginInit();
            //_bmp.UriSource = new Uri(_data.cover_image, UriKind.RelativeOrAbsolute);
            //_bmp.EndInit();
            //PART_Icon.ImageSource = _bmp;

            PART_Title.Text = _data.title;
            PART_Number.Text = _data.number.ToString();
            PART_CatName.Text = _data.cat_name;
            PART_Time.Text = _data.createtime_text;
        }

        public void Load_Image()
        {
            if (Data == null || string.IsNullOrEmpty(Data.cover_image)) return;

            Load_Image(Data.cover_image);
        }

        void Load_Image(string _url)
        {
            using (var _client = new WebClient())
            {
                _client.Proxy = null;
                _client.DownloadDataCompleted += (s, e) =>
                {
                    if (e.Result != null && e.Result.Length > 0)
                    {
                        try
                        {
                            BitmapImage _bmp = new BitmapImage();
                            _bmp.CacheOption = BitmapCacheOption.OnLoad;
                            _bmp.BeginInit();
                            _bmp.StreamSource = new MemoryStream(e.Result);
                            _bmp.EndInit();

                            PART_Icon.ImageSource = _bmp;
                        }
                        catch (Exception ex)
                        {
                            App.Log(ex);
                        }
                    }
                };
                _client.DownloadDataAsync(new Uri(_url, UriKind.RelativeOrAbsolute));
            }
        }

        void PART_Download_Click(object sender, RoutedEventArgs e)
        {
            if(_is_downloading)
            {
                ShowDialogView _view = new ShowDialogView() { ShowDialogContent = "正在下载，请等待" };
                _view.ShowDialog();
                return;
            }

            ShowDialogView3 showDialogView = new ShowDialogView3();
            showDialogView.ShowDialogContent = "是否下载该资源包";
            if (showDialogView.ShowDialog() == true)
            {
                SaveFileDialog sfd = new SaveFileDialog();
                sfd.Filter = "Zip包|*.zip";
                sfd.FilterIndex = 1;
                sfd.FileName = Path.GetFileName(Data.zippath);
                sfd.RestoreDirectory = true;
                if (sfd.ShowDialog() == true)
                {
                    string _url = Data.zippath;
                    PART_Progress.Value = 0;
                    PART_Progress.Visibility = Visibility.Visible;
                    new Thread(new ThreadStart(() =>
                    {
                        _is_downloading = true;
                        try
                        {
                            using (var _client = new WebClient())
                            {
                                _client.Proxy = null;
                                _client.DownloadProgressChanged += (s, args) =>
                                {
                                    Dispatcher.Invoke(new Action(() =>
                                    {
                                        PART_Progress.Value = args.ProgressPercentage;
                                    }));
                                };
                                _client.DownloadFileCompleted += (s, args) =>
                                {
                                    Dispatcher.Invoke(new Action(() =>
                                    {
                                        if (args.Error != null)
                                        {
                                            ShowDialogView _view = new ShowDialogView() { ShowDialogContent = "下载备课包失败!\r\n" + args.Error.Message };
                                            _view.ShowDialog();
                                        }
                                        else
                                        {
                                            ShowDialogView _view = new ShowDialogView() { ShowDialogContent = "下载成功!" };
                                            _view.ShowDialog();
                                        }
                                        PART_Progress.Value = 0;
                                        PART_Progress.Visibility = Visibility.Collapsed;
                                    }));
                                    _is_downloading = false;
                                };
                                _client.DownloadFileAsync(new Uri(_url, UriKind.RelativeOrAbsolute), sfd.FileName);
                            }
                        }
                        catch (Exception ex)
                        {
                            App.Log(ex);
                            _is_downloading = false;
                        }
                    }))
                    { IsBackground = true }.Start();
                }
            }
            //if (DownloadCallback != null) DownloadCallback(this.Data);
        }

        void PART_Delete_Click(object sender, RoutedEventArgs e)
        {
            if (DeleteCallback != null) DeleteCallback(this.Data);
        }

        void PART_Share_Click(object sender, RoutedEventArgs e)
        {
            if (ShareCallback != null) ShareCallback(this.Data);
        }

        void PART_Edit_Click(object sender, RoutedEventArgs e)
        {
            if (EditCallback != null) EditCallback(this.Data);
        }

        void PART_Top_Click(object sender, RoutedEventArgs e)
        {
            if (TopCallback != null) TopCallback(this.Data);
        }

        void PART_Lesson_Click(object sender, RoutedEventArgs e)
        {
            if (LessonCallback != null) LessonCallback(this.Data);
        }

        bool _is_downloading;
    }
}
